package com.salton123.whiteboard.utils

import android.graphics.Path
import android.util.Log
import androidx.core.graphics.PathParser
import org.w3c.dom.Element
import java.io.InputStream
import javax.xml.parsers.DocumentBuilderFactory

/**
 * User: wujinsheng1@yy.com
 * Date: 2020/5/22 11:03
 * ModifyTime: 11:03
 * Description:
 */
object SVGHelper {
    const val TAG = "SVGHelper"

    /**
     * 读取Path字段
     */
    fun parsePath(inputStream: InputStream): ArrayList<Path?> {
        //只取第一个
        val resgions: ArrayList<Path?> = ArrayList()
        try {
            val documentElement = DocumentBuilderFactory
                .newInstance()
                .newDocumentBuilder()
                .parse(inputStream)
                .documentElement
            val split = documentElement.getAttribute("viewBox").split(" ".toRegex())
                .dropLastWhile { it.isEmpty() }.toTypedArray()
            val width = java.lang.Float.parseFloat(split[2])
            val height = java.lang.Float.parseFloat(split[3])
            Log.e(TAG, "width :$width, height :$height")
            val elementsByTagName2 = documentElement.getElementsByTagName("path")
            for (j in 0 until elementsByTagName2.length) {
                val element2 = elementsByTagName2.item(j) as Element
                val attribute2 = element2.getAttribute("d")
                resgions.add(PathParser.createPathFromPathData(attribute2))
            }
        } catch (tx: Throwable) {
            Log.e(TAG, tx.toString())
        }
        return resgions
    }

}